package org.vogelsk.archangelsk.ai;

import java.util.List;

import org.vogelsk.archangelsk.creatures.GenericCreature;
import org.vogelsk.archangelsk.creatures.Tank;
import org.vogelsk.archangelsk.util.Command;
import org.vogelsk.archangelsk.util.Direction;

public class Commander {

	private List<Tank> tanks;
	private GenericCreature target;

	public void command() {
		if(!getTanks().isEmpty()){
		for (Tank tank : getTanks()) {
			if (isTargetInSight(tank))
				tank.setOrder(Command.SUPPORT_FIRE);
			else
				tank.setOrder(Command.MANOUVER);
		}
		}

	}

	private boolean isTargetInSight(Tank tank) {
		if ((tank.getDirection().equals(Direction.UP)&&(target.getY() < tank.getY())) 
			||((tank.getDirection().equals(Direction.DOWN))&&(target.getY() > tank.getY())))
		{
			return visibilityFunction(target.getY(),tank.getY(),target.getX(),tank.getX());
		}
		
		if ((tank.getDirection().equals(Direction.LEFT)&&(target.getX() < tank.getX())) 
				||((tank.getDirection().equals(Direction.RIGHT))&&(target.getX() > tank.getX())))
			{
			return visibilityFunction(target.getX(),tank.getX(),target.getY(),tank.getY());			
			}


		return false;

	}

	private boolean visibilityFunction(int arga1, int arga2, int argb1, int argb2){
		
		if (((Math.abs(arga1 - arga2)) - 3*(Math.abs(argb1 - argb2)))>0)
			return true;
		else return false;
	}
	
	public GenericCreature getTarget() {
		return target;
	}

	public void setTarget(GenericCreature target) {
		this.target = target;
	}

	public void setTanks(List<Tank> tanks) {
		this.tanks = tanks;
	}

	public List<Tank> getTanks() {
		return tanks;
	}
}
